package com.qiaotongtianxia.loans.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.qiaotongtianxia.loans.R;
import com.qiaotongtianxia.loans.functionInterface.IBaseRequestImp;
import com.qiaotongtianxia.loans.net.Api;
import com.qiaotongtianxia.loans.util.Constants;
import com.qiaotongtianxia.loans.util.ToastUtil;
import com.qiaotongtianxia.loans.views.BaseEditText;
import com.qiaotongtianxia.loans.views.BaseProgress;
import com.qiaotongtianxia.loans.views.BaseTextView;
import com.qiaotongtianxia.loans.views.ButtonObserver;
import com.qiaotongtianxia.loans.views.CashEditText;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by lisen on 2017/12/16.
 * 上传还款凭证
 *
 * @author lisen < 4533548588@qq.com >
 */

public class UploadRefundLiceseActivity extends BaseActivity {
    private static final int LICENCE = 400;
    @BindView(R.id.tv_nav_title)
    BaseTextView tvNavTitle;
    @BindView(R.id.et_refundOrderId)
    BaseEditText etRefundOrderId;
    @BindView(R.id.et_refundAmount)
    CashEditText etRefundAmount;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.btn_confirm)
    ButtonObserver btnConfirm;

    private SparseArray<String> sparseArray = new SparseArray<>();
    private HashMap<String, String> map = new HashMap<>();//存储上传文件的路径和上传后返回的值

    private String id;
    @Override
    public int getLayoutId() {
        return R.layout.activity_upload_refund;
    }

    @Override
    public Api onApiCreate() {
        return new Api(this);
    }
    @Override
    public void onBaseCreate(@Nullable Bundle savedInstanceState) {
        btnConfirm.observers(etRefundOrderId,etRefundAmount);
        btnConfirm.setExtraEnable(false);
        id = getIntent().getStringExtra(Constants.REFUND_ID);
    }

    @OnClick({R.id.iv_nav_back, R.id.iv_pic, R.id.btn_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_nav_back:
                finish();
                break;
            case R.id.iv_pic:
                String licencePath = sparseArray.get(LICENCE);
                if (!TextUtils.isEmpty(licencePath)){
                    //打开预览
                    openPreview(licencePath,LICENCE);
                }else{
                    requestPermission(
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.CAMERA}, LICENCE);
                }
                break;
            case R.id.btn_confirm:
                if (map.size() != 1){
                    map.clear();
                    uploadImgs();
                }else{
                    commit();
                }
                break;
        }
    }

    private void commit() {
        BaseProgress progress = api.getProgress();
        if (progress != null){
            progress.setProgressTip(getString(R.string.wait));
        }
        String orderId = etRefundOrderId.getText().toString();
        String amount = etRefundAmount.getText().toString();
        String orderImg = map.get(sparseArray.get(LICENCE));
        api.refund(id, orderId, amount, orderImg, new IBaseRequestImp<String>() {
            @Override
            public void onRequestSuccess(String s) {
                ToastUtil.showShort(UploadRefundLiceseActivity.this,s);
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    /**
     * 上传图片
     */
    private void uploadImgs() {
        BaseProgress progress = api.getProgress();
        for (int i = 0; i < sparseArray.size(); i++) {
            if (progress != null){
                progress.setProgressTip("上传中...");
            }
            final String path = sparseArray.valueAt(i);
            api.uploadImg(new File(path), new IBaseRequestImp<String>() {
                @Override
                public void onRequestSuccess(String s) {
                    map.put(path,s);
                    if (map.size() == 1){
                        commit();
                    }
                }
            });
        }
    }
    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null){
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0){
                    ImageItem imageItem = images.get(0);
                    String path= imageItem.path;

                    compressPhoto(requestCode,path);

                    switch (requestCode){
                        case LICENCE:
                            Glide.with(this).load(path).into(ivPic);
                            break;
                    }
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images == null || images.size() == 0){
                    String path = sparseArray.get(requestCode);
                    if (map.containsKey(path)){
                        map.remove(path);
                    }
                    sparseArray.remove(requestCode);
                    switch (requestCode){
                        case LICENCE:
                            Glide.with(this).load(R.drawable.icon_addpic).into(ivPic);
                            break;
                    }
                }
                if (sparseArray.size() == 1){
                    btnConfirm.setExtraEnable(true);
                }else{
                    btnConfirm.setExtraEnable(false);
                }
            }
        }
    }
    private void compressPhoto(final int requestCode, final String photo){
        Luban.with(this)
                .load(photo)
                .ignoreBy(300)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onSuccess(File file) {
                        sparseArray.put(requestCode,file.getPath());
                        if (sparseArray.size() == 1){
                            btnConfirm.setExtraEnable(true);
                        }else{
                            btnConfirm.setExtraEnable(false);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {}
                }).launch();
    }

    private String getPath() {
        String path = Constants.PATH;
        File file = new File(path);
        if (file.mkdirs()) {
            createNomedia(path);
            return path;
        }
        createNomedia(path);
        return path;
    }

    private void createNomedia(String path) {
        File nomedia = new File(path,".nomedia");
        if (!nomedia.exists()){
            try {
                nomedia.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打开预览
     * @param path
     * @param requestCode
     */
    private void openPreview(String path,int requestCode){
        Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
        ArrayList<ImageItem> list = new ArrayList<>();
        ImageItem imageItem = new ImageItem();
        imageItem.path = path;
        list.add(imageItem);
        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, list);
        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, 0);
        intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
        startActivityForResult(intentPreview, requestCode);
    }

    @Override
    public void permissionSuccess(int requestCode) {
        //添加图片
        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void permissionFail(final int requestCode) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("无法获取权限")
                .setNegativeButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("再次获取", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                            requestPermission(
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.CAMERA}, requestCode);
                    }
                }).show();
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(this,R.color.gray));
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(this,R.color.mainColor));
    }
    @Override
    public void initTitle() {
        tvNavTitle.setText(getString(R.string.uploadRefundLicence));
    }
}
